package server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;


/** A server that serves one client */
public class Server {
	private HashMap<String, LinkedList<String>> users; // username and
	// read permission
	private HashMap<String, Boolean> createRecordPermissions; // if a user has
	// permission to
	// create new
	// records
	private ArrayList<String> patients;
	private Logger logger = new Logger();
	private SSLConnection sslc;

	public final static int LOGIN = 0;
	public final static int GET_LIST = 1;
	public final static int GET_RECORD = 2;
	public final static int NEW_RECORD = 3;
	public final static int LOGOFF = 4;
	
	public final static String rcrdDir = "Records";

	public static void main(String args[]) {
		Server s = new Server();
	}

	public Server() {
		sslc = new SSLConnection(this);
		setUp();
	}

	/**
	 * Läser in användare och patienter från filer.
	 */
	public void setUp() {

	}



	public void authenticateClient() {

	}

	/** 
	 * Kontrollera att användaren finns (och har rätt lösenord senare). 
	 */
	public boolean verifyUser(String uName) {
		return users.containsKey(uName);
	}

	/**
	 * Skapar en ny journal om användaren har rätt till det.
	 * @throws FileNotFoundException 
	 */
	public void createRecord(String uName, Record rcrd) throws FileNotFoundException {
		if (createRecordPermissions.get(uName)) {
			
			File file = new File(rcrd.fileName());
			PrintWriter out = new PrintWriter(file);
			out.write(rcrd.toString());

			patients.add(rcrd.getName());
			logger.log((new Date()).toString() + "New record: "
					+ rcrd.getName() + " created by " + uName);
		} else {
			// log?
		}
	}

	public void endSession() {
		// onödig??
	}

	/**
	 * Skickar journalen om användaren har rätt att se den.
	 */
	public void getRecord(String uName, String rcrdName) {
		if(users.get(uName).contains(rcrdName)) {
			File file = new File(rcrdName + ".rcd");
			SSLConnection.sendRecord(file.toString());
		}
	}

	/**
	 * Skickar en lista på alla journaler användaren har rätt att se.
	 */
	public void getRecordList(String name) {

	}

	public void fileList(){
		File folder = new File("c:/");
		File[] listOfFiles = folder.listFiles();

 
		listOfFiles[1].getName();
	}
}
